package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.Cate;
import com.itheima.ydd.service.CateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/ydd_cate")
public class CateController {
    @Autowired
    private CateService cateService;

    /**
     * 分类详情
     *
     * @param id
     */
    @GetMapping("/rowInfo")
    public ResultData getCate(String id) {
        Cate cate = cateService.getById(id);
        return ResultData.ok("", cate);
    }

    /**
     * 分类列表-分页
     *
     * @param catename
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public ResultData page(String catename, Integer page, Integer limit) {
        //构造分页构造器对象
        Page<Cate> catePage = new Page<>(page, limit);
        //条件构造器
        LambdaQueryWrapper<Cate> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(catename), Cate::getCateName, catename);
        cateService.page(catePage, wrapper);
        return ResultData.ok("",PageResult.init(catePage.getTotal(),catePage.getCurrent(),catePage.getSize(),catePage.getRecords()));
    }

    /**
     * 分类删除
     *
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResultData delete(String id) {
        cateService.removeById(id);
        return ResultData.ok("删除分类信息成功", null);
    }

    /**
     * 分类修改
     *
     * @param cate
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody Cate cate) {
        cateService.updateById(cate);
        return ResultData.ok("修改分类信息完成", null);
    }

    /**
     * 分类添加
     *
     * @param cate
     * @return
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody Cate cate) {
        cateService.save(cate);
        return ResultData.ok("添加分类信息成功", null);
    }

    /**
     * 分类列表-全部
     * @return
     */
   @GetMapping("/all")
    public ResultData getAll(){
       List<Cate> cateList = cateService.list();
       return ResultData.ok("",cateList);
   }
}
